<template>
  <div>
    <div>
      <el-row :gutter="24">
        <el-col :span="2">
    <el-button @click="exportToExcel">导出表格</el-button>
    <!--limit:最大上传数，on-exceed：超过最大上传数量时的操作  -->
        </el-col>
        <el-col :span="2">
    <el-upload
      class="upload-demo"
      action=""
      :on-change="handleChange"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :limit="limitUpload"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
      :auto-upload="false"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <!-- <div slot="tip" class="el-upload__tip">只 能 上 传 xlsx / xls 文 件</div> -->
    </el-upload>
        </el-col>
        <el-col :span="8">
      <input style="width:100%" type="text" placeholder="按主页名称或编号搜索" v-model="inputKey" />
        </el-col>
        <el-col :span="12">
      <div v-for="(item, index) in search(inputKey)" :key="index">
          <p>文件名：{{ item.name }} 编号：{{ item.code }}</p>
      </div>
        </el-col>
      </el-row>
    </div>
    <!-- 数据展示 -->
    <el-main>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-input-number v-model="datainfo.code" placeholder="请输入编号">
          </el-input-number>
        </el-col>
        <el-col :span="5">
          <el-input
            v-model="datainfo.name"
            placeholder="请输入文件名"
          ></el-input>
        </el-col>
        <el-col :span="5">
          <el-input
            v-model="datainfo.path"
            placeholder="请输入文件路径"
          ></el-input>
        </el-col>
        <el-col :span="5">
          <el-input
            v-model="datainfo.tag"
            placeholder="请输入文件标签"
          ></el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" @click="adddata">增加</el-button>
        </el-col>
      </el-row>
      <el-table :data="da">
        <el-table-column prop="code" label="编号"> </el-table-column>
        <el-table-column prop="name" label="文件名"> </el-table-column>
        <el-table-column prop="path" label="路径"> </el-table-column>
        <el-table-column prop="tag" label="标签"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="editdata(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button size="mini" type="danger" @click="deldata(scope.$index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <!-- 编辑 -->
    <el-dialog title="编辑" :visible.sync="isedit">
      <el-form ref="form" :model="newdata" label-width="60px">
        <el-form-item label="编号">
          <el-input
            v-model="newdata.code"
            autocomplete="off"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件名">
          <el-input v-model="newdata.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文件路径">
          <el-input v-model="newdata.path" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文件标签">
          <el-input v-model="newdata.tag" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isedit = false">取 消</el-button>
        <el-button type="primary" @click="saveedit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const dataList = [
  {
    key: "1",
    name: "Brown John",
    age: 32,
    tel: "0571-22098909",
    phone: 18889898989,
    address: "New York No. 1 Lake Park",
  },
  {
    key: "2",
    name: "Jim Green",
    tel: "0571-22098333",
    phone: 18889898888,
    age: 42,
    address: "London No. 1 Lake Park",
  },
  {
    key: "3",
    name: "Joe Black",
    age: 32,
    tel: "0575-22098909",
    phone: 18900010002,
    address: "Sidney No. 1 Lake Park",
  },
  {
    key: "4",
    name: "Jim Red",
    age: 18,
    tel: "0575-22098909",
    phone: 18900010002,
    address: "London No. 2 Lake Park",
  },
  {
    key: "5",
    name: "Jake White",
    age: 18,
    tel: "0575-22098909",
    phone: 18900010002,
    address: "Dublin No. 2 Lake Park",
  },
];
import Vue from "vue";
export default {
  data() {
    return {
      dataList,
      limitUpload: 1,
      fileTemp: null,
      file: null,
      da: [],
      isdel: false,
      isedit: false,
      newdata: {
        code: 0,
        name: "",
        path: "",
        tag: "",
      },
      datainfo: {
        code: 0,
        name: "",
        path: "",
        tag: "",
      },
      listindex: 0,
      dalen: 0,
      inputKey: "",
    };
  },
  methods: {
    adddata() {
      if (this.datainfo.name.trim().length <= 0) {
        return this.$message.warning("文件名不能为空");
      }
      if (this.datainfo.path.trim().length <= 0) {
        return this.$message.warning("路径不能为空");
      }
      if (this.datainfo.tag.trim().length <= 0) {
        return this.$message.warning("标签不能为空");
      }
      this.da.push(this.datainfo);
      this.datainfo = {
        code: 0,
        name: "",
        path: "",
        tag: "",
      };
    },
    editdata(listindex, item) {
      this.listindex = listindex;
      this.newdata = {
        code: item.code,
        name: item.name,
        path: item.path,
        tag: item.tag,
      };
      this.isedit = true;
    },
    deldata(index) {
      this.$confirm("确认删除？")
        .then((_) => {
          // eslint-disable-line no-unused-vars
          this.da.splice(index, 1);
        })
        .catch((_) => {}); // eslint-disable-line no-unused-vars
    },
    saveedit() {
      if (this.newdata.name.trim().length <= 0) {
        return this.$message.warning("文件名不能为空");
      }
      if (this.newdata.path.trim().length <= 0) {
        return this.$message.warning("路径不能为空");
      }
      if (this.newdata.tag.trim().length <= 0) {
        return this.$message.warning("标签不能为空");
      }
      this.isedit = false;
      Vue.set(this.da, this.listindex, this.newdata);
    },
    exportToExcel() {
      require.ensure([], () => {
        //  ---require 括号里面是是引用  Export2Excel.js  可以使绝对路径也可以是相对路径
        const { export_json_to_excel } = require("@/excel/Export2Excel.js");
        // 设置Excel的表格第一行的标题
        const tHeader = ["编号", "文件名", "路径", "标签"];
        // 'code', 'name', 'path', 'tag'是tableData里对象的属性
        const filterVal = ["code", "name", "path", "tag"];
        const list = this.da; //把data里的tableData存到list
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, "列表excel");
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    handleChange(file, fileList) {
      this.fileTemp = file.raw;
      if (this.fileTemp) {
        if (
          this.fileTemp.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemp.type == "application/vnd.ms-excel"
        ) {
          this.importfxx(this.fileTemp);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！",
        });
      }
    },
    handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    handleRemove(file, fileList) {
      this.fileTemp = null;
    },
    importfxx(obj) {
      let _this = this;
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据
      this.file = event.currentTarget.files[0];
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = function (e) {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
          console.log("未处理的原始数据如下：");
          console.log(outdata);
          _this.da = outdata;
          console.log("da:");
          console.log(_this.da);
          //此处可对数据进行处理
          let arr = [];
          outdata.map((v) => {
            let obj = {};
            obj.code = v["编号"];
            obj.name = v["文件名"];
            obj.path = v["路径"];
            obj.tag = v["标签"];
            arr.push(obj);
          });
          _this.da = arr;
          _this.dalen = arr.length;
          return arr;
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    search(indexKey) {
      if (indexKey == null) {
        return this.da;
      } else {
        return this.da.filter((item) => {
          if (item.name.includes(indexKey)) {
            return item;
          }
        });
      }
    },
  },
};
</script>

<style scoped>
</style>